package dao

import (
	"context"
	"sale-admin/internal/dal"
	"time"

	"github.com/golang-module/carbon/v2"
	"gorm.io/gorm"
)

type GoodsClick struct{}

type GoodsClickNum struct {
	GoodsID  string `json:"goods_id"`
	ClickNum int64  `json:"click_num"`
}

// 获取机器单日点击量
func (GoodsClick) GetDailyGoodsClick(ctx context.Context, db *gorm.DB, robotName, goodsID, date string) (res []GoodsClickNum, err error) {
	if robotName == "" && goodsID == "" {
		return
	}
	m := dal.Use(db).MaGoodsClick
	tx := m.WithContext(ctx)
	if robotName != "" {
		tx = tx.Where(m.RobotName.Eq(robotName))
	}
	if goodsID != "" {
		tx = tx.Where(m.GoodsID.Eq(goodsID))
	}
	if date != "" {
		tx = tx.Where(m.CreatedDate.Eq(carbon.ParseByLayout(date, carbon.DateLayout).ToStdTime()))
	}
	tx.Select(m.GoodsID, m.ClickNum.Sum().As(m.ClickNum.ColumnName().String())).
		Group(m.GoodsID).
		Scan(&res)
	return
}

// 按商品分组的商品点击量
type GoodsClickList struct {
	GoodsID  string `json:"goods_id"`
	ClickNum int64  `json:"click_num"`
}

func (GoodsClick) GetGoodsClick(ctx context.Context, db *gorm.DB, goodsID string, startTime, endTime int64) (res []GoodsClickList, err error) {
	var start, end time.Time
	if startTime == 0 && endTime == 0 {
		start = carbon.Now().StartOfDay().ToStdTime()
		end = carbon.Now().EndOfDay().ToStdTime()
	} else {
		start = carbon.CreateFromTimestamp(startTime).ToStdTime()
		end = carbon.CreateFromTimestamp(endTime).ToStdTime()
	}
	m := dal.Use(db).MaGoodsClick
	tx := m.WithContext(ctx)
	if goodsID != "" {
		tx = tx.Where(m.GoodsID.Eq(goodsID))
	}
	tx.Where(m.StartTime.Between(start, end)).
		Group(m.GoodsID).
		Select(m.GoodsID, m.ClickNum.Sum().As(m.ClickNum.ColumnName().String())).
		Scan(&res)
	return
}
